from sqlalchemy import create_engine, Column, Integer, DateTime, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from dynaconf import Dynaconf

# 加载配置
settings = Dynaconf(
    settings_files=['config/config.yaml'],
    environments=True
)

# 创建数据库引擎
DATABASE_URL = f"{settings.database.driver}://{settings.database.username}:{settings.database.password}@{settings.database.host}:{settings.database.port}/{settings.database.database}"
engine = create_engine(DATABASE_URL, echo=settings.app.debug)

# 创建会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 基础模型类
Base = declarative_base()

# 获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 示例模型基类，包含通用字段
class BaseModel(Base):
    """表模型基类，包含公共字段"""
    __abstract__ = True
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")
